# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
        def dfs(node, stack):
            ans = None
            if node is None:
                return None
            ans = dfs(node.left, stack)
            if ans:
                return ans
            if len(stack) > 0 and stack[len(stack)-1].val == p.val:
                return node
            stack.append(node)
            ans = dfs(node.right, stack)
            if ans:
                return ans
        return dfs(root, [])
        